<template>
    <el-upload
        ref="uploadRef"
        :action="UpLoadUrl"
        list-type="picture-card"
        :with-credentials="true"
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
        :limit="1"
        :on-exceed="handleExceed"
        :file-list="fileList"
    >
        <el-icon><Plus /></el-icon>
        <template #file="{ file }">
            <div class="cover">
                <el-icon><Delete @click="handleRemove" /></el-icon>
                <img :src="file.url" class="avatar" />
            </div>
        </template>
    </el-upload>
</template>

<script setup>
import { Plus, Delete } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { UpLoadUrl } from "@/config";
import { ref } from "vue";

const uploadRef = ref(null);
const url = ref("");
const fileList = ref([]);

// 上传成功
const handleSuccess = (res, file) => {
    if (res.code == "1") {
        url.value = res.data.url;
        fileList.value = [{ name: file.name, url: res.data.url }];
    } else {
        ElMessage.error(res.message);
    }
};

// 上传之前
const beforeUpload = (file) => {
    if (file.type.indexOf("image") === -1) {
        ElMessage.error("只支持JPG/JPEG/PNG图片上传");
        return false;
    }
    if (file.size > 1024 * 1024 * 5) {
        ElMessage.error("图片不能大于5MB");
        return false;
    }
    return true;
};
// 覆盖上传
const handleExceed = (files, fileList) => {
    uploadRef.value.clearFiles();
    uploadRef.value.handleStart(files[0]);
};

// 删除文件
const handleRemove = (file, fileList) => {
    uploadRef.value.clearFiles();
    url.value = "";
    fileList.value = [];
};

defineExpose({
    getUrl: () => url.value,
    setUrl: (newUrl) => {
        url.value = newUrl;
        fileList.value = newUrl ? [{ name: "已上传图片", url: newUrl }] : [];
    },
    clearFiles: () => {
        uploadRef.value.clearFiles();
        url.value = "";
        fileList.value = [];
    }
});
</script>

<style lang="scss" scoped>
.cover {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    position: relative;
    .el-icon {
        position: absolute;
        left: 0px;
        top: 0px;
        width: 100%;
        height: 100%;
        color: #fff;
        font-size: 32px;
        transition: 0.3s;
        opacity: 0;
        background-color: rgba(0, 0, 0, 0.4);
        svg {
            cursor: pointer;
        }
    }
    &:hover {
        .el-icon {
            opacity: 1;
        }
    }
    img {
        width: 98%;
    }
}
</style>
